﻿using Microsoft.Data.SqlClient;
using Microsoft.Win32;
using System.IO;
using System.Reflection.Metadata;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;

namespace SQLScriptExecutor
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private const int MaxLines = 1000;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void SelectFile_Click(object sender, RoutedEventArgs e)
        {
            // 创建一个 OpenFileDialog 实例
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                // 设置初始目录
                InitialDirectory = "C:\\",
                // 设置标题
                Title = "Select a File",
                // 设置过滤器，只显示特定类型的文件
                Filter = "Text files (*.sql)|*.txt|All files (*.*)|*.*"
            };

            // 显示对话框并检查用户是否点击了“确定”按钮
            if (openFileDialog.ShowDialog() == true)
            {
                // 获取用户选择的文件路径
                string filePath = openFileDialog.FileName;
                // 更新 TextBlock 控件以显示所选文件的路径
                txtFilePath.Text = filePath;
            }
        }

        private void Start_Click(object sender, RoutedEventArgs e)
        {
            string connectionString = $"Data Source={txtServer.Text};Initial Catalog=master;User ID={txtUserName.Text};Password={txtPassword.Password};Encrypt=True;TrustServerCertificate=True;";

            var filePath = txtFilePath.Text;

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                try
                {
                    connection.Open();
                    Console.WriteLine("连接成功");

                    // 使用 StreamReader 流式读取 SQL 文件
                    using (StreamReader reader = new StreamReader(filePath))
                    {
                        StringBuilder batch = new StringBuilder();
                        string? line;
                        SqlCommand command = connection.CreateCommand();

                        // 设置CommandTimeout为0意味着没有超时限制
                        command.CommandTimeout = 0;

                        while ((line = reader.ReadLine()) != null)
                        {
                            // 忽略空行和注释
                            if (string.IsNullOrWhiteSpace(line) || line.TrimStart().StartsWith("--"))
                                continue;

                            // 添加当前行到批处理
                            batch.AppendLine(line);

                            // 检查是否遇到了分隔符
                            if (line.Trim().EndsWith("GO", StringComparison.OrdinalIgnoreCase))
                            {
                                batch.Remove(batch.Length - 4, 4); // 移除最后的 "GO"

                                if (batch.Length > 0)
                                {
                                    command.CommandText = batch.ToString();

                                    // 执行批处理命令
                                    command.ExecuteNonQuery();
                                }

                                batch.Clear(); // 清空批处理以开始新的一个
                            }
                        }

                        // 执行最后一个批处理（如果有的话）
                        if (batch.Length > 0)
                        {
                            command.CommandText = batch.ToString();
                            command.ExecuteNonQuery();
                        }
                    }

                    MessageBox.Show("所有SQL语句执行完毕");
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"发生错误: {ex.Message}");
                }
                finally
                {
                    if (connection.State == System.Data.ConnectionState.Open)
                        connection.Close();
                }
            }
        }
    }
}
